package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.VipServiceConfigService;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class VipUpdateUserPaidRecord implements UpdateUserPaidRecordStrategy {

    @Autowired
    private UserInfoService userInfoService ;

    @Autowired
    private VipServiceConfigService vipServiceConfigService ;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper ;

    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("VipUpdateUserPaidRecord...updateUserPaidRecord...执行了");

        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();

        // 根据用户的id查询用户信息
        UserInfo userInfo = userInfoService.getById(userId);

        // 保存vip的购买信息到user_vip_service表中
        UserVipService userVipService = new UserVipService() ;
        userVipService.setOrderNo(orderNo);
        userVipService.setUserId(userPaidRecordVo.getUserId());

        // 计算vip购买信息的开始时间和过期时间
        Date startTime = new Date() ;
        if(userInfo.getIsVip().intValue() == 1 && userInfo.getVipExpireTime().after(startTime)) {     // 是vip用户，并且vip没有过期
            userVipService.setStartTime(userInfo.getVipExpireTime());
        }else {
            userVipService.setStartTime(startTime);
        }

        // 获取startTime的值
        // 获取用户购买的vip的配置信息的id
        Long vipConfigId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigService.getById(vipConfigId);
        DateTime vipExpireTime = DateUtil.offset(userVipService.getStartTime(), DateField.MONTH, vipServiceConfig.getServiceMonth());
        userVipService.setExpireTime(vipExpireTime);
        userVipServiceMapper.insert(userVipService) ;

        // 更新用户信息
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(vipExpireTime);
        userInfoService.updateById(userInfo) ;

        // Redis中的用户数据是否需要更新： 使用Canal进行数据同步的

    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_VIP;  // 1003
    }
}
